import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken, getTenantId} from '@/utils/auth'
import router, {asyncRoutes, resetRouter, constantRoutes} from '@/router'
import Layout from "@/layout";
import store from "@/store";
import {loginVerify, findUserByWorkNumber} from "@/api/table";

const state = {
  token: getToken(),
  tenantId: getTenantId(),
  name: '',
  loginInfo: {},
  roles: [],
  routerListDA: [],
  routerListA: [],  //工作站路由列表
  routerListB: [],  //患者管理路由列表
  severFall: {},
  ssoStatus: '',
  darkThemeColor: false,
  isAuto: true, //dark主题切换是否手动
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_TENANT: (state, tenantId) => {
    state.tenantId = tenantId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_routeList: (state, data) => {
    state.routerListDA = data
  },
  SET_routeListA: (state, data) => {
    state.routerListA = data
  },
  SET_routeListB: (state, data) => {
    state.routerListB = data
  },
  SET_severFall: (state, data) => {
    state.severFall = data
  },
  //添加单点登录的状态信息
  SET_ssoStatus: (state, data) => {
    state.ssoStatus = data
  },
  SET_loginInfo: (state, data) => {
    state.loginInfo = data
  }
}

const actions = {
  // user
  loginVerify({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      const {loginId, captcha} = userInfo
      loginVerify({loginId: loginId, captcha: captcha}).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user getUserByUserId
  findUserByWorkNumber({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      const {loginid} = userInfo
      findUserByWorkNumber({loginid: loginid}).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user login
  login({commit}, userInfo) {
    const {loginName, password,tenantId} = userInfo
    return new Promise((resolve, reject) => {
      login({loginName: loginName.trim(), password: password,tenantId: tenantId}).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const {data} = response;
        if (!data) {
          reject('用户验证失败，请重新登录！')
        }

        const {roles, userName, menu} = data;
        if (!roles || roles.length <= 0) {
          reject('用户没有登录权限！');
        }
        commit('SET_loginInfo', data);

        commit('SET_ROLES', roles);
        commit('SET_NAME', userName);

        const isWorkList = []; // 工作台列表
        const patientManagementList = []; // 病人管理列表
        let routesData = []; //不同权限角色的路由列表
        let menuList = [];  //角色菜单

        //根据权限筛选路由列表
        if (roles.includes('超级管理员')) {
          routesData = asyncRoutes;
        } else {
          if (menu.length != 0) {
            //角色管理分配权限时，只选择部分子菜单导致menu中没有父菜单id,需添加以显示
            let arr;
            menu.map(item =>{
              menuList.push(item);

              //如果menulist中,不包含子菜单涉及的父菜单id，则添加
              arr = item.split('-');
              if(arr.length == 2 && !menuList.includes(arr[0])){
                menuList.push(arr[0]);
              }
            });

            asyncRoutes.map((route) => {
              if (typeof (route.id) == "undefined") {
                routesData.push(route);
              } else {
                //权限分配的菜单一定有children，children一定有id
                if (menuList.includes(route.id)) {
                  route.children = route.children.filter((item) =>
                    menuList.includes(item.id)
                  )
                  routesData.push(route);
                }
              }
            });
          }
        }

        routesData.map((item) => {
          if (item.type === 'isWork') {
            isWorkList.push(item);
          } else if (item.type === 'patientManagement') {
            patientManagementList.push(item);
          } else {
            isWorkList.push(item);
            patientManagementList.push(item);
          }
        });

        commit('SET_routeList', routesData)
        commit('SET_routeListA', isWorkList)
        commit('SET_routeListB', patientManagementList)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {root: true})

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // 暂存数据
  restseverFall({commit}, data) {
    return new Promise(resolve => {
      commit('SET_severFall', data)
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
